import subprocess
import shutil
import os
import re

def run_command(command):
    """运行给定的命令"""
    try:
        result = subprocess.run(command, check=True, shell=True, text=True, capture_output=True)
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"命令执行失败: {e.stderr}")
        raise

def package_and_upload():
    """打包并上传到 PyPI"""
    # 清空 dist 目录
    dist_dir = 'dist'
    if os.path.exists(dist_dir):
        shutil.rmtree(dist_dir)
        print(f"已清空 {dist_dir} 目录")

    # 自动增加版本号
    update_version()

    # 打包命令
    package_command = "python setup.py sdist bdist_wheel"
    print(f"执行命令: {package_command}")
    run_command(package_command)

    # 上传命令
    upload_command = "twine upload dist/*"
    print(f"执行命令: {upload_command}")
    run_command(upload_command)

def update_version():
    """自动增加 setup.py 中的版本号"""
    setup_file = 'setup.py'
    with open(setup_file, 'r') as file:
        content = file.read()

    # 使用正则表达式查找版本号
    version_pattern = r"version\s*=\s*['\"](\d+\.\d+\.\d+)['\"]"
    match = re.search(version_pattern, content)
    if not match:
        raise ValueError("无法找到版本号")

    current_version = match.group(1)
    version_parts = current_version.split('.')
    version_parts[-1] = str(int(version_parts[-1]) + 1)
    new_version = '.'.join(version_parts)

    # 替换版本号
    new_content = re.sub(version_pattern, f"version='{new_version}'", content)

    # 写回 setup.py
    with open(setup_file, 'w') as file:
        file.write(new_content)

    print(f"版本号已更新为: {new_version}")

if __name__ == "__main__":
    package_and_upload()